/**
教程地址：http://www.ng-newsletter.com/posts/chrome-apps-on-angular.html

api文档：http://api.wunderground.com/weather/api/d/docs
郑州预报：http://api.wunderground.com/global/stations/57083.html?MR=1
**/


angular.module('weather')
// 接受一个服务名以及一个定义实际程序的函数
.provider('WeatherService', function() {
	var apiKey = 'b10491ac823d123e';

	this.setApiKey = function(key){
		if(key) this.apiKey = key;
	};
	// build http://api.wunderground.com/api/b10491ac823d123e/forecast/q/CA/San_Francisco.json
	// http://api.wunderground.com/api/b10491ac823d123e/forecast/lang:CN/q/France/Paris.json
	// http://api.wunderground.com/api/b10491ac823d123e/geolookup/conditions/forecast/lang:CN/q/Beijing,Beijing.json
	// http://api.wunderground.com/api/b10491ac823d123e/geolookup/conditions/forecast/lang:CN/q/Zhengzhou,Henan.json
	this.getUrl = function(type,city){
		var strArr = ['http://api.wunderground.com/api/',apiKey,
				'/',type,'/lang:CN/q/',city,'.json'];
		return  strArr.join('');
	}
	this.$get = function($q, $http) {
	  var self = this;
	  return {
	    getWeatherForecast: function(city) {
	      var d = $q.defer();
	      $http({
	        method: 'GET',
	        url: self.getUrl("forecast", city),
	        cache: true
	      }).success(function(data) {
	        // The wunderground API returns the 
	        // object that nests the forecasts inside
	        // the forecast.simpleforecast key
	        console.log(data);
	        d.resolve(data.forecast.simpleforecast);
	      }).error(function(err) {
	        d.reject(err);
	      });
	      return d.promise;
	    },
	    getCityDetails: function(query) {
		  var d = $q.defer();
		  $http({
		    method: 'GET',
		    url: 'http://autocomplete.wunderground.com/' + 'aq?query=' + query,
		    cache: true
		  }).success(function(data) {
		    d.resolve(data.RESULTS);
		  }).error(function(err) {
		    d.reject(err);
		  });
		  return d.promise;
		}
	  }
	}
})

.factory('UserService', function() {
  var defaults = {
    location: 'autoip'
  };

  var service = {
    user: {},
    save: function() {
      sessionStorage.presently =
        angular.toJson(service.user);
    },
    restore: function() {
      // Pull from sessionStorage
      service.user = 
        angular.fromJson(sessionStorage.presently) || defaults

      return service.user;
    }
  };
  // Immediately call restore from the session storage
  // so we have our user data available immediately
  service.restore();
  return service;
})

.directive('autoFill', function($timeout) {
  return {
    restrict: 'EA',
    scope: {
      autoFill: '&',
      ngModel: '='
    },
    compile: function(tEle, tAttrs) {
        var tplEl = angular.element('<div class="typeahead">' +
		  '<input type="text" autocomplete="off" />' +
		  '<ul id="autolist" ng-show="reslist">' +
		    '<li ng-repeat="res in reslist" ' +
		      '>{{res.name}}</li>' +
		  '</ul>' +
		  '</div>');
		var input = tplEl.find('input');
		input.attr('type', tAttrs.type);
		input.attr('ng-model', tAttrs.ngModel);
		tEle.replaceWith(tplEl);

      return function(scope, ele, attrs, ctrl) {
        

		  var minKeyCount = attrs.minKeyCount || 3,
		      timer,
		      input = ele.find('input');

		  input.bind('keyup', function(e) {
		    val = ele.val();
		    if (val.length < minKeyCount) {
		      if (timer) $timeout.cancel(timer);
		      scope.reslist = null;
		      return;
		    } else {
		      if (timer) $timeout.cancel(timer);
		      timer = $timeout(function() {
		        scope.autoFill()(val)
		        .then(function(data) {
		          if (data && data.length > 0) {
		            scope.reslist = data;
		            scope.ngModel = data[0].zmw;
		          }
		        });
		      }, 300);
		    }
		  });
		  // Hide the reslist on blur
		  input.bind('blur', function(e) {
		    scope.reslist = null;
		    scope.$digest();
		  });
      }
    }
  }
})